package com.tekj.cxqcb.view.Module.activity.Order;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suke.widget.SwitchButton;
import com.tekj.cxqcb.MainBActivity;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.config.enums.EventBusMsgBean;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.DoGetCaristForBrandBean;
import com.tekj.cxqcb.operation.resultBean.DoGetFinancialPlanByCarIdBean;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.SelectCarByColorBean;
import com.tekj.cxqcb.view.Module.activity.BrandActivity;
import com.tekj.cxqcb.view.Module.adapter.FinancialProgrammeAdapter;
import com.tekj.cxqcb.view.Module.adapter.PopListAdapter;
import com.tekj.cxqcb.view.Module.bean.NewOrderBean;
import com.tekj.cxqcb.view.Module.bean.PopListBean;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import es.dmoral.toasty.Toasty;

import static android.view.Gravity.BOTTOM;
import static com.tekj.cxqcb.view.Module.activity.Order.CarOrderDetailsActivity.orderData;

/**
 * 新建订单
 */
public class NewOrdersActivity extends BaseActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_id)
    EditText etId;
    @BindView(R.id.et_credit_line)
    EditText etCreditLine;
    @BindView(R.id.tv_Vehicle_type)
    TextView tvVehicleType;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_price_gps)
    TextView tvPriceGps;
    @BindView(R.id.tv_Purchase_Tax)
    TextView tvPurchaseTax;
    @BindView(R.id.tv_price_bx)
    TextView tvPriceBx;
    @BindView(R.id.tv_price_sx)
    TextView tvPriceSx;
    @BindView(R.id.tv_jzdqx)
    TextView tvJzdqx;
    @BindView(R.id.tv_dkqd)
    TextView tvDkqd;
    @BindView(R.id.tv_cpfa)
    TextView tvCpfa;
    @BindView(R.id.tv_dkqs)
    TextView tvDkqs;
    @BindView(R.id.tv_sfbl)
    TextView tvSfbl;
    @BindView(R.id.tv_sfje)
    TextView tvSfje;
    @BindView(R.id.tv_zrze)
    TextView tvZrze;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_monthly_pay)
    TextView tvMonthlyPay;
    @BindView(R.id.sb_isDqx)
    SwitchButton sbIsDqx;
    @BindView(R.id.ll_body)
    LinearLayout llBody;
    @BindView(R.id.img_Arrow1)
    ImageView imgArrow1;
    @BindView(R.id.tv_car_color)
    TextView tvCarColor;
    @BindView(R.id.img_Arrow2)
    ImageView imgArrow2;


    PopListAdapter listAdapter, carListAadpter;
    List<PopListBean> listBeans;

    BusinessDao businessDao;
    NewOrderBean orderBean;
    FinancialProgrammeAdapter programmeAdapter;


    static int orderType;
    static String shopname;
    String sfbl;

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
        orderType = getIntent().getIntExtra("type", 0);

        shopname = orderType == 1 ? orderData.getOrder().getShopName() : getIntent().getStringExtra("shopname");

        tvTitle.setText(orderType == 1 ? "修改进件信息" : "新建订单");

        businessDao = new BusinessDao(activity, this);

        orderBean = new NewOrderBean(getIntent().getStringExtra("id"),
                getIntent().getStringExtra("userid"),
                MainBActivity.User.getUserId(),
                MainBActivity.User.getName(),
                MainBActivity.User.getPhone());
        initAdapter();
        sbIsDqx.setVisibility(View.INVISIBLE);


        sbIsDqx.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (carData != null)
                    businessDao.DoGetDkze(carData.getId(), isChecked ? 0 : 1, sfbl);
                else
                    businessDao.DoGetDkze(orderBean.getCarId(), isChecked ? 0 : 1, sfbl);
                orderBean.setJzqdx(isChecked ? 1 : 0);
            }
        });
        if (orderType == 1) {
            initData();
        }

    }


    void initAdapter() {

        listBeans = new ArrayList<>();
        listBeans.add(new PopListBean(1, "新1", false));
        listBeans.add(new PopListBean(2, "新2", false));
        listBeans.add(new PopListBean(3, "常规", false));

        listAdapter = new PopListAdapter(listBeans);
        listAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (carData == null) {
                    Toasty.normal(activity, "请先选择购买车型").show();
                    return;
                }
                tvCpfa.setText(listAdapter.getData().get(position).getTitle());
                orderBean.setCpfn(listAdapter.getData().get(position).getId());
                businessDao.DoGetFinancialPlanByCarId(carData.getId(), 2);
                popupWindow.dismiss();
            }
        });

        programmeAdapter = new FinancialProgrammeAdapter(null);
        programmeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (programmeAdapter.getData() == null) {
                    Toasty.normal(activity, "产品方案未选择").show();
                    return;
                }
                tvDkqs.setText(programmeAdapter.getData().get(position).getCycle());
                tvSfbl.setText(programmeAdapter.getData().get(position).getDownPayments());
                sfbl = programmeAdapter.getData().get(position).getDownPayments();
                tvSfje.setText(programmeAdapter.getData().get(position).getDownPayPrice());
                tvMonthlyPay.setText("￥ " + programmeAdapter.getData().get(position).getMonPrice());
                orderBean.setPlanId(programmeAdapter.getData().get(position).getFinancialPlanId());
                popupWindow.dismiss();
                businessDao.DoGetDkze(orderBean.getCarId(), sbIsDqx.isChecked() ? 0 : 1, sfbl);

            }
        });

        carListAadpter = new PopListAdapter(null);

        carListAadpter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                tvCarColor.setText(carListAadpter.getData().get(position).getTitle());
                orderBean.setColor(carListAadpter.getData().get(position).getTitle());

                popupWindow.dismiss();
            }
        });
    }

    @Override
    public int setLayout() {
        return R.layout.activity_new_orders;
    }

    @Override
    public void initLoadStart() {
        showDialog();
    }

    @Override
    public void initLoadEnd() {
        dialog.dismiss();
    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 金融方案:
                DoGetFinancialPlanByCarIdBean byCarIdBean = (DoGetFinancialPlanByCarIdBean) bindingViewBean.getBean();
                if (byCarIdBean.getCode().equals("0000000")) {
                    programmeAdapter.setNewData(byCarIdBean.getData().getList());
                }
                break;
            case 总融资额:
                PubStatusBean pubStatusBean = (PubStatusBean) bindingViewBean.getBean();
                if (pubStatusBean.getCode().equals("0000000")) {
                    tvZrze.setText(pubStatusBean.getData().getZdke());
                    tvJzdqx.setText(pubStatusBean.getData().getJzqdx());
                    tvMonthlyPay.setText(pubStatusBean.getData().getYg());
                    tvPriceGps.setText(pubStatusBean.getData().getXmrgps());
                }
                break;
            case 根据车型查颜色:
                SelectCarByColorBean selectCarByColorBean = (SelectCarByColorBean) bindingViewBean.getBean();
                if (selectCarByColorBean.getCode().equals("0000000")) {
                    List<PopListBean> listBeans = new ArrayList<>();
                    for (SelectCarByColorBean.DataBean.CarListBean car : selectCarByColorBean.getData().getCarList()) {
                        listBeans.add(new PopListBean(0, car.getColor(), false));
                    }
                    carListAadpter.setNewData(listBeans);
                }
                break;
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    @OnClick({R.id.ll_back, R.id.tv_Vehicle_type, R.id.tv_type,
            R.id.tv_price, R.id.tv_dkqd, R.id.tv_cpfa,
            R.id.tv_dkqs, R.id.tv_sfbl, R.id.tv_sfje,
            R.id.tv_zrze, R.id.tv_next, R.id.tv_car_color})
    public void onViewClicked(View view) {
        Intent intent = null;
        int code = 0;
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_car_color:
                if (!isModify()) {
                    return;
                }
                if (carListAadpter.getData() != null && carListAadpter.getData().size() > 0)
                    showPop(carListAadpter);
                else {
                    Toasty.normal(activity, "请先选择车型").show();
                }
                break;
            case R.id.tv_Vehicle_type:
                if (!isModify()) {
                    return;
                }
                intent = new Intent(activity, BrandActivity.class);
                code = 101;
                break;
            case R.id.tv_type:

                break;
            case R.id.tv_price:

                break;
            case R.id.tv_dkqd:

                break;
            case R.id.tv_cpfa:
                if (!isModify()) {
                    return;
                }
                showPop(listAdapter);
                break;
            case R.id.tv_dkqs:
                if (!isModify()) {
                    return;
                }
                Toasty.normal(activity, "期数暂时无法选择").show();
                break;
            case R.id.tv_sfbl:
                if (!isModify()) {
                    return;
                }
                showPop(programmeAdapter);
                break;
            case R.id.tv_sfje:

                break;
            case R.id.tv_zrze:

                break;
            case R.id.tv_next:

                if (orderBean.getCarId() == null) {
                    Toasty.normal(activity, "请先选择车型").show();
                    return;
                }
                if (orderBean.getColor() == null) {
                    Toasty.normal(activity, "请先选择车辆颜色").show();
                    return;
                }
                if (orderBean.getCpfn() == 0) {
                    Toasty.normal(activity, "请先选择产品方案").show();
                    return;
                }
                if (orderBean.getPlanId() == null || orderBean.getPlanId().equals("")) {
                    Toasty.normal(activity, "请先选择首付比例").show();
                    return;
                }


                startActivity(new Intent(activity, NewOrdersTwoActivity.class)
                        .putExtra("bean", orderBean)
                );
                break;
        }
        if (intent != null) {
            if (code != 0) {
                startActivityForResult(intent, code);
            } else
                startActivity(intent);

        }
    }

    DoGetCaristForBrandBean.DataBean.ListBean carData;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case 101:
                    carData = (DoGetCaristForBrandBean.DataBean.ListBean) data.getSerializableExtra("brand");
                    businessDao.SelectCarByColor(carData.getId());
                    setData();
                    break;

            }
        }
    }

    /**
     * 设置数据
     */
    void setData() {
        orderBean.setCarId(carData.getId());
        tvVehicleType.setText(carData.getTitle());
        tvPrice.setText(carData.getPlatformPrice() + "");
        tvPurchaseTax.setText(carData.getRgzs() + "");
        tvPriceBx.setText(carData.getInsurance() + "");
        tvPriceGps.setText(carData.getGps() + "");
        tvPriceSx.setText(carData.getProcedureMoney() + "");
        sbIsDqx.setVisibility(View.VISIBLE);
        //初始化数据
        tvCpfa.setText("");
        tvSfbl.setText("");
        tvDkqs.setText("");
        tvSfje.setText("");
        tvMonthlyPay.setText("");

        orderBean.setCpfn(0);
        orderBean.setPlanId("");

        if (!sbIsDqx.isChecked())
            businessDao.DoGetDkze(carData.getId(), 1, sfbl);
        sbIsDqx.setChecked(false);
    }


    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    private void showPop(RecyclerView.Adapter adapter) {
        Tools.lightoff(activity);
        popupView = View.inflate(activity, R.layout.pop_list, null);
        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);


        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);

        View view = popupView.findViewById(R.id.view_miss);
        view.setVisibility(View.GONE);

        RecyclerView rvScreen = popupView.findViewById(R.id.rv_main);
        rvScreen.setLayoutManager(new LinearLayoutManager(activity));
        rvScreen.setHasFixedSize(true);
        rvScreen.setAdapter(adapter);
        rvScreen.addItemDecoration(new SpacesItemDecoration(5));
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Tools.lighton(activity);
            }
        });

        popupWindow.showAtLocation(rlTitleBg, BOTTOM, 0, 0);
        popupView.startAnimation(animation);

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void Event(EventBusMsgBean e) {
        switch (e.getmEnumStatus()) {
            case 订单关闭:
                finish();
                break;
        }
    }

    /**
     * 当有数据时展示数据并且初始化orderData
     */
    void initData() {

        tvVehicleType.setText(orderData.getDetail().getTitle());

        tvPrice.setText(orderData.getDetail().getPlatformPrice() + "");
        tvPurchaseTax.setText(orderData.getDetail().getRgzs() + "");
        tvPriceBx.setText(orderData.getDetail().getInsurance() + "");

        tvPriceGps.setText(orderData.getDetail().getXmgpsfy() + "");

        tvPriceSx.setText(orderData.getAutomobile().getProcedureMoney() + "");

        sbIsDqx.setVisibility(View.VISIBLE);
        sbIsDqx.setEnabled(isModify());
        sbIsDqx.setChecked(!orderData.getDetail().getJzqdx().equals("0"));

        tvCpfa.setText(listBeans.get(orderData.getDetail().getLoanType() - 1).getTitle());

        tvSfbl.setText(orderData.getPlan().getDownPayments());

        sfbl = orderData.getPlan().getDownPayments();

        tvDkqs.setText(orderData.getPlan().getCycle());
        tvSfje.setText(orderData.getOrder().getDownPay());

        tvNext.setText(isModify() ? "下一步" : "查看附件");

        tvCarColor.setText(orderData.getDetail().getColor());

//        tvZrze.setText(orderData);
        tvMonthlyPay.setText(orderData.getOrder().getMonPay());
        orderBean.setId(orderData.getOrder().getId());
        orderBean.setCarId(orderData.getDetail().getCarId());
        orderBean.setCpfn(orderData.getDetail().getLoanType());
        orderBean.setPlanId(orderData.getDetail().getPlanId());
        orderBean.setColor(orderData.getDetail().getColor());


        imgArrow1.setVisibility(isModify() ? View.VISIBLE : View.INVISIBLE);
        imgArrow2.setVisibility(isModify() ? View.VISIBLE : View.INVISIBLE);

        businessDao.DoGetDkze(orderBean.getCarId(), sbIsDqx.isChecked() ? 0 : 1, sfbl);
        businessDao.DoGetFinancialPlanByCarId(orderBean.getCarId(), 2);

        businessDao.SelectCarByColor(orderBean.getCarId());
    }

    /**
     * 判断是否可以修改订单
     *
     * @return false(不可修改)
     */
    public static boolean isModify() {
        if (orderType == 1 && orderData.getOrder().getOrderStatus() != 2) {
            return false;
        }
        return true;
    }

}
